package com.itsenpupulai.longlivetest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import de.tavendo.autobahn.WebSocketConnection;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String TAG = "MainActivity";

    private Button connectBtn;
    private Button disconnectBtn;
    private TextView messageTv;
    private EditText sendMsgEdit;
    private Button sendMsgBtn;
    private Intent webSocketServiceIntent;

    private static Context context;


    private BroadcastReceiver imReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WebSocketService.WEBSOCKET_ACTION.equals(action)) {
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    String msg = bundle.getString("message");
                    if (!TextUtils.isEmpty(msg))
                        getMessage(msg);
                }

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webSocketServiceIntent = new Intent(this, WebSocketService.class);
        startService(webSocketServiceIntent);
        context = this;
        initView();
    }

    private void initView(){
        connectBtn = (Button)findViewById(R.id.connect_btn);
        disconnectBtn = (Button)findViewById(R.id.disconnect_btn);
        messageTv = (TextView)findViewById(R.id.message_tv);
        sendMsgEdit = (EditText)findViewById(R.id.send_msg_edit);
        sendMsgBtn = (Button)findViewById(R.id.send_msg_btn);
        connectBtn.setOnClickListener(this);
        disconnectBtn.setOnClickListener(this);
        sendMsgBtn.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.connect_btn:
//                WebSocketService.webScoketConnect();
                getlogindata();
                break;

            case R.id.disconnect_btn:
                WebSocketService.closeWebsocket(false);
                handler.removeCallbacks(runable);
                break;

            case R.id.send_msg_btn:
               handler.post(runable);
                break;
        }
    }
    // handler定时器，循环上传坐标，好像比timer好用
    private static Runnable runable = new Runnable() {
        @Override
        public void run() {
            WebSocketService.sendMsg(SocketData.getLocationData(context));
            handler.postDelayed(this, 5000);
        }
    };

    private static Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    WebSocketService.sendMsg(SocketData.getLocationData(context));
//                    handler.sendEmptyMessageDelayed(1, 500);
                    runable.run();
                    break;
                case 2:
                    String result = (String) msg.obj;
                    Log.e(TAG, "登陆请求结果：--》" + result);
                    if (result == null){
                        Toast.makeText(context, "数据为空", Toast.LENGTH_SHORT).show();
                    }else{
                        try {
                            int code = new JSONObject(result).getInt("code");
                            if (code == 200){
                                Toast.makeText(context, "请求成功", Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(context, "请求异常", Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }


                    break;
            }


        }
    };


    private void getMessage(String msg){
        messageTv.setText("");
        messageTv.setText(msg);
    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter(WebSocketService.WEBSOCKET_ACTION);
        registerReceiver(imReceiver,filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(imReceiver);
    }


    private void getlogindata() {
        OkHttpClient httpClient = new OkHttpClient();

        TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        String szImei = TelephonyMgr.getDeviceId();
        if (szImei == null) {
            szImei = Settings.Secure.getString(this.getContentResolver(),
                    Settings.Secure.ANDROID_ID);
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("user_mobile", "18137173079");
        map.put("imei", szImei);
        map.put("user_flag", "3");
        map.put("device", "1");
            map.put("token", "de2134adde135sdfe9aeddaefg");
        map.put("jgid", "14ggh3");
        map.put("user_pwd", "111111");
        map.put("method", "kkpb.user.login");
        NetUtils.post(this, map, new com.zhy.http.okhttp.callback.Callback() {
            @Override
            public Object parseNetworkResponse(Response response) throws Exception {
                Log.e(TAG, "请求结果" + response.body().string());
                String result = response.body().string();
                String code = new JSONObject(result).getString("code");
                if ("200".equals(code)){
                    WebSocketService.webScoketConnect();
                }else{
                    Toast.makeText(MainActivity.this, "信息加载失败", Toast.LENGTH_SHORT).show();
                }


                Log.e(TAG, "请求结果 --- code--- " + code);
                return null;
            }

            @Override
            public void onError(Call call, Exception e) {

//                Log.e(TAG, "请求失败" );
            }

            @Override
            public void onResponse(Call call, Object o) {

            }
        });


    }

}
